<template>
  <div
    class="h-full bg-white flex flex-col"
    :style="{ height: c_height + 'px', borderRadius: '8px' }"
  >
    <div class="flex justify-between" style="border-bottom: 1px solid #e5e7eb">
      <div class="flex items-center ml-1">
        <UnorderedListOutlined title="切换到列表模式" @click="handleChangeList" />
      </div>
      <div class="flex justify-end gap-10px p-10px">
        <Button type="primary" class="mr-1" @click="handleAdd" v-if="canAdd">
          <template #icon><PlusOutlined /></template>
          {{ btnAddName }}
        </Button>
        <Button type="primary" class="mr-1" v-if="listPage.isAdmin" @click="handleManager">
          <template #icon><SettingOutlined /></template>
          管理
        </Button>
      </div>
    </div>
    <div class="overflow-auto flex-1">
      <div class="flex flex-wrap justify-center gap-10px list m-t-10px">
        <div class="w-190px list_box" v-for="item in dataSource" :key="item.id">
          <div class="w-190px h-120px">
            <template
              v-if="
                imageField &&
                item[`${imageField}_meta_data`] &&
                item[`${imageField}_meta_data`].length
              "
            >
              <Image
                :width="190"
                :height="120"
                :src="`${baseUrl}showImg.do?visitKey=${
                  item[`${imageField}_meta_data`][0].visitKey
                }&path=${item[`${imageField}_meta_data`][0].path}`"
              />
            </template>
          </div>
          <div class="text-center">
            <div
              class="overflow_text p-5px"
              :title="item[grid]"
              v-for="grid in listPage.gridShowField"
              :key="grid"
              >{{ item[grid] }}</div
            >
          </div>
          <div
            class="flex justify-around items-center operate"
            v-if="item.colOperate && item.colOperate.length"
          >
            <div
              class="cursor-pointer"
              v-for="(el, index) in item.colOperate"
              :key="index"
              @click.stop="handleColOperate(el, item)"
            >
              {{ el.name }}
            </div>
          </div>
        </div>
        <div
          style="border: none; height: 0"
          class="w-200px list_box"
          v-for="item in dataSource.length < 6 ? dataSource.length * 6 : dataSource.length"
          :key="`box${item.id}`"
        >
        </div>
      </div>
    </div>
    <div class="flex justify-end mt-2 h-50px pr-10px" v-if="listPage.isPagination">
      <Pagination
        v-model:current="searchForm.page"
        v-model:pageSize="searchForm.pageSize"
        :total="searchForm.total"
        @change="paginationChange"
        size="small"
        :show-total="(total) => `共 ${total} 条数据`"
      />
    </div>
    <ProcessShowDrawer @register="registerProcessShowDrawer" />
    <ProcessDrawer @register="registerProcessDrawer" @success="handleSuccess" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, unref, nextTick, computed, h } from 'vue';
  import { getVisualList, getVisualDel, getVisualListRelate } from '/@/api/module/module';
  import { SettingOutlined, PlusOutlined, UnorderedListOutlined } from '@ant-design/icons-vue';
  import { Image, Button } from 'ant-design-vue';
  import { useUserStore } from '/@/store/modules/user';
  import { isArray } from '/@/utils/is';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useDrawer } from '/@/components/Drawer';
  import { getFlowInit } from '/@/api/process/process';
  import ProcessDrawer from '../processManagement/processDrawer.vue';
  import ProcessShowDrawer from '../processManagement/processShowDrawer.vue';
  import { getParams } from '/@/utils/utils';
  import * as useFormJsFunc from '/@/assets/form_js';
  import { useGo } from '/@/hooks/web/usePage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { Pagination } from 'ant-design-vue';
  import { useEventListener } from '/@/hooks/event/useEventListener';

  export default defineComponent({
    name: 'CardList',
    components: {
      SettingOutlined,
      PlusOutlined,
      Image,
      ProcessDrawer,
      ProcessShowDrawer,
      Pagination,
      Button,
      UnorderedListOutlined,
    },
    props: {
      listPageInfo: {
        type: Object,
        default: () => {
          return {};
        },
      },
      treeNodeCode: {
        type: String,
        default: '',
      },
      isTreeView: {
        type: Boolean,
        default: false,
      },
    },
    emits: ['handle-manager', 'handle-add', 'handle-edit', 'handle-click', 'change-list'],
    setup(props, { emit }) {
      const [registerProcessShowDrawer, { openDrawer: openProcessShowDrawer }] = useDrawer();
      const [registerProcessDrawer, { openDrawer: openProcessDrawer }] = useDrawer();
      const go = useGo();
      const { t } = useI18n();

      const { createMessage, createConfirm } = useMessage();
      const userStore = useUserStore();
      const serverInfo = userStore.getServerInfo;
      const baseUrl = computed(() =>
        serverInfo.rootPath?.endsWith('/') ? serverInfo.rootPath : `${serverInfo.rootPath}/`,
      );
      const canAdd = computed(() => props.listPageInfo.isBtnAddShow);
      const canEdit = computed(() => props.listPageInfo.isBtnEditShow);
      const canDel = computed(() => props.listPageInfo.isBtnDelShow);
      const btnAddName = computed(() => props.listPageInfo.btnAddName || '新增');
      const btnEditName = computed(() => props.listPageInfo.btnEditName || '编辑');
      const btnDelName = computed(() => props.listPageInfo.btnDelName || '删除');
      const listPage = ref<Recordable>({});
      const pageSetup = ref<Recordable[]>([]);
      const imageField = ref('');
      const searchForm = ref({
        moduleCode: '',
        total: 0,
        page: 1,
        pageSize: 10,
        action: 'search',
      });

      const isListRelate = ref(false);
      const getListUrl = computed(() => {
        return isListRelate.value ? getVisualListRelate : getVisualList;
      });

      const dataSource = ref<any>([]);

      const getListUrlData = async () => {
        const api = getListUrl.value;
        const res = await api(searchForm.value);
        console.log('getListUrlData res', res);
        dataSource.value = res?.list;
        searchForm.value.total = res?.total;
      };
      const c_height = ref(0);

      const fetch = async (params = {}, isRelate = false) => {
        isListRelate.value = isRelate;
        console.log('isListRelate.value', isListRelate.value);

        await nextTick();
        imageField.value = '';
        listPage.value = props.listPageInfo;
        if (listPage.value.gridShowField) {
          if (!isArray(listPage.value.gridShowField)) {
            listPage.value.gridShowField = listPage.value.gridShowField.split(',');
            //取第一个字段作为图片显示
            imageField.value = listPage.value.gridShowField.shift();
            // listPage.value.gridShowField.shift();
            console.log('listPage.value.gridShowField', listPage.value.gridShowField);
          }
        } else {
          listPage.value.gridShowField = [];
        }
        console.log('fetch listPage', listPage.value);

        // setProps({ api: getListUrl.value, title: unref(listPage)?.moduleName });
        pageSetup.value = unref(listPage).pageSetup || [];
        pageSetup.value.forEach((item) => {
          if (isArray(item.blocks)) {
            item.blocks.forEach((col) => {
              col.style = {
                backgroundColor: col.bgColor ? col.bgColor : 'transparent',
                font: col.font ? col.font : '',
                fontSize: col.fontSize ? col.fontSize + 'px' : '14px',
                fontWeight: col.isBold == 'true' ? 'bold' : '400',
                color: col.fontColor,
                textAlign: col.align ? col.align : 'left',
                paddingTop: col.paddingTop ? col.paddingTop + 'px' : '0',
                paddingBottom: col.paddingBottom ? col.paddingBottom + 'px' : '0',
                paddingLeft: col.paddingLeft ? col.paddingLeft + 'px' : '0',
                paddingRight: col.paddingRight ? col.paddingRight + 'px' : '0',
                marginTop: col.marginTop ? col.marginTop + 'px' : '0px',
                marginRight: col.marginRight ? col.marginRight + 'px' : '0',
                marginBottom: col.marginBottom ? col.marginBottom + 'px' : '0',
                marginLeft: col.marginLeft ? col.marginLeft + 'px' : '0',
                width: '100%',
              };
              if (col.type == 'field') {
                col.style.width = '100%';
                col.style.height = '100%';
              }

              if (col.bgImgUrl) {
                col.style.background = 'url(' + unref(baseUrl) + col.bgImgUrl + ') no-repeat';
                col.style.backgroundSize = '100% 100%';
              }
            });
          }
        });
        // if (listPage.value.isColCheckboxShow) {
        //   setProps({
        //     rowSelection: {
        //       type: 'checkbox',
        //     },
        //   });
        // }
        // if (!listPage.value.isPagination) {
        //   setProps({
        //     pagination: false,
        //   });
        // }

        // setPagination({
        //   pageSize: listPage.value.pageSize,
        // });

        searchForm.value = {
          ...searchForm.value,
          ...params,
        };
        calcHeight();
        getListUrlData();
      };

      const calcHeight = () => {
        c_height.value = window.innerHeight - 160;
        if (document.getElementById('customForm')?.clientHeight) {
          c_height.value = c_height.value - document.getElementById('customForm')?.clientHeight;
        }
        console.log('c_height', c_height.value);
      };

      useEventListener({
        el: window,
        name: 'resize',

        listener: () => {
          calcHeight();
        },
      });

      function handleSuccess() {
        console.log('handleSuccess');
        fetch();
      }

      const handleManager = () => {
        emit('handle-manager');
      };
      const handleAdd = () => {
        emit('handle-add');
      };

      //单个删除
      function handleDelete(record: object) {
        createConfirm({
          iconType: 'info',
          title: () => h('span', t('common.prompt')),
          content: () => h('span', '您确定要删除么'),
          onOk: async () => {
            getVisualDel({
              ids: record['id'],
              moduleCode: listPage.value.moduleCodeRelated
                ? listPage.value.moduleCodeRelated
                : listPage.value.moduleCode,
              treeNodeCode: props.treeNodeCode,
              isTreeView: props.isTreeView,
            }).then(() => {
              handleSuccess();
            });
          },
        });
      }

      const handleClick = (row) => {
        emit('handle-click', row);
      };

      /**
       * 跳转到其它模块，用于二次开发
       * goTo('/smartModulePage', {
       *  moduleCode: 'xmxxgl',
       *  xm: xmId,
       * })
       */
      function goTo(path: string, query: any) {
        go({
          path,
          query,
        });
      }

      function handleColOperate(col, record) {
        console.log('col.name', col.name);
        console.log('record', record);
        let item = record['colOperate'].filter((it) => col.name == it.name)[0];
        console.log('handleColOperate item', item);
        if (item.type == 'FLOW_SHOW') {
          // 查看流程详情
          openProcessShowDrawer(true, {
            flowId: item.flowId,
            visitKey: item.visitKey,
          });
        } else if (item.type == 'FLOW') {
          // 发起流程
          let params = {
            op: 'opLinkFlow',
            typeCode: item.flowTypeCode,
            ...item,
          };
          getFlowInit(params).then((res) => {
            let myActionId = res.myActionId || '';
            if (myActionId) {
              openProcessDrawer(true, {
                myActionId: myActionId,
                type: res.type,
              });
            }
          });
        } else if (item.type == 'MODULE') {
          goTo('/smartModulePage', {
            moduleCode: item.moduleCode,
            moduleId: record.id,
          });
        } else if (item.type == 'CLICK') {
          // 如果存在动态引入的js
          if (typeof useFormJsFunc[listPage.value.formCode] === 'function') {
            console.log('CLICK launch script');
            // const funcs = [reload];
            const funcs = [];
            useFormJsFunc[listPage.value.formCode](item.script, funcs).then((ret) => {
              console.log('useFormJsFunc[' + listPage.value.formCode + ']', ret);
              if (!ret) {
                console.log('CLICK eval script after useFormJsFunc');
                // 调用外部 js
                try {
                  eval(item.script);
                } catch (e) {
                  console.warn(item.name, e);
                }
              }
            });
          } else {
            // 调用外部 js
            console.log('CLICK eval script');
            try {
              eval(item.script);
            } catch (e) {
              console.warn(item.name, e);
            }
          }
        } else if (item.type == 'LINK') {
          let params = getParams(item.link);
          goTo(item.link, { ...params });
        } else if (item.type == 'DEL') {
          handleDelete(record);
        } else if (item.type == 'EDIT') {
          emit('handle-edit', record);
        } else if (item.type == 'SHOW') {
          handleClick(record);
        }
      }

      const paginationChange = () => {
        fetch();
      };

      //切换到列表
      const handleChangeList = () => {
        emit('change-list');
      };

      return {
        handleSuccess,
        listPage,
        handleManager,
        fetch,
        pageSetup,
        baseUrl,
        handleAdd,
        canAdd,
        canDel,
        canEdit,
        btnAddName,
        btnDelName,
        btnEditName,
        handleClick,
        handleColOperate,
        registerProcessShowDrawer,
        registerProcessDrawer,
        dataSource,
        searchForm,
        paginationChange,
        c_height,
        handleChangeList,
        imageField,
      };
    },
  });
</script>
<style lang="less" scoped>
  .overflow_text {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .list {
    &_box {
      position: relative;
      // border: 1px solid #e5e7eb;
      .operate {
        width: 100%;
        background-color: rgba(0, 0, 0, 0.5); // #0084f4b0;
        color: #fff;
        position: absolute;
        transition: height 0.3s ease; /* 动画过渡效果 */
        bottom: 0;
        height: 0;
        opacity: 0;
      }
      &:hover {
        .operate {
          height: 30px;
          opacity: 1;
        }
      }
    }
  }

  :deep(.ant-image) {
    display: flex;
    justify-content: center;
  }

  :deep(.ant-image-img) {
    object-fit: cover;
    height: 100%;
  }
</style>
